/**
 * 
 */
package com.ly.mpayment.core.secuity;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;



/**  
 *   
 * 项目名称：backend-web  
 * 类名称：AES  
 * 类描述： 
 * 创建时间：2013年9月9日上午11:20:44
 * 修改备注：  
 * @version   
 *   
 */
public class AES {

//	public static final String VIPARA = "0102030405060708";  
	public static final String VIPARA = "telecom_wap_2018";  
	public static final String bm = "utf-8";  
	
	public static String encrypt(String data,String keyStr, String iv)
			throws Exception {
//		dataPassword = fillKey(dataPassword);
		IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes());
		SecretKeySpec key = new SecretKeySpec(keyStr.getBytes(), "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
		byte[] encryptedData = cipher.doFinal(iv.getBytes(bm));
		return Base64.encode(encryptedData);
	}

	public static String decrypt(String data,String keyStr,String iv)
			throws Exception {
//		dataPassword = fillKey(dataPassword);
		byte[] byteMi = Base64.decode(data);
		IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes());
		SecretKeySpec key = new SecretKeySpec(keyStr.getBytes(), "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
		byte[] decryptedData = cipher.doFinal(byteMi);

		return new String(decryptedData,bm);
	}
	
	/**
	 * key不满16位的时候后面追加0补满16位
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unused")
	private static String fillKey(String key){
		if(key!=null && key.length()<16){
			int remaining = 16-key.length();
			for(int i=0;i<remaining;i++){
				key+="0";
			}
		}
		return key;
	}

	@SuppressWarnings("unused")
	public static void main(String[] args) {
		try {
			
			String serPwd = MD5.md5("123456");
			String secretKey = serPwd.substring(0, 16);
			String iv = serPwd.substring(16, 32);
			String encode = encrypt("18081091080",secretKey, iv);
			System.out.println(encode);
//			System.out.println(DaHanSanTongUtil.recharge("18621764382", "30", "201609211133"));
			
			
//			System.out.println(encode);
//			System.out.println(decrypt("111111", encode));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		
	}
}
